<template>
  <teleport to="#message">
    <div
      class="alert message-info w-50 mx-auto fade show fixed-top d-flex justify-content-between align-items-center mt-2"
      :class="classSelect"
      v-if="isVisible"
    >
      <span>{{ message }}</span>
      <button type="button" class="btn" @click="hide">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
  </teleport>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch } from 'vue';
import createNode from '../hooks/useCreateDom';
export type MessageType = 'success' | 'error' | 'default';
export default defineComponent({
  props: {
    message: String,
    type: {
      type: String as PropType<MessageType>,
      default: 'default'
    }
  },
  setup(props, context) {
    createNode('message');
    const isVisible = ref(true);
    const classSelect = {
      'alert-success': props.type === 'success',
      'alert-danger': props.type === 'error',
      'alert-primary': props.type === 'default'
    };
    watch(
      isVisible,
      newV => {
        if (newV) {
          setTimeout(() => {
            isVisible.value = false;
          }, 2000);
        }
      },
      { deep: true, immediate: true }
    );
    const hide = () => {
      isVisible.value = false;
      context.emit('close-message');
    };
    return { classSelect, isVisible, hide };
  }
});
</script>

<style></style>
